package com.xx.library.service.impl;

import com.xx.library.entity.Book;
import com.xx.library.mapper.BookMapper;
import com.xx.library.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class BookServiceImpl implements BookService {

    @Autowired
    private BookMapper bookMapper;

    @Override
    public Book getBookById(Long id) {
        return bookMapper.selectById(id);
    }

    @Override
    public Book getBookByIsbn(String isbn) {
        return bookMapper.selectByIsbn(isbn);
    }

    @Override
    public List<Book> getAllBooks() {
        return bookMapper.selectAll();
    }

    @Override
    public List<Book> getBooksByCondition(Book book) {
        return bookMapper.selectByCondition(book);
    }

    @Override
    public void addBook(Book book) {
        // 检查ISBN是否已存在
        if (getBookByIsbn(book.getIsbn()) != null) {
            throw new RuntimeException("ISBN已存在");
        }
        // 设置初始可借数量等于总数量
        book.setAvailableCopies(book.getTotalCopies());
        book.setStatus(1);
        bookMapper.insert(book);
    }

    @Override
    public void updateBook(Book book) {
        Book existingBook = getBookById(book.getId());
        if (existingBook == null) {
            throw new RuntimeException("书籍不存在");
        }
        bookMapper.update(book);
    }

    @Override
    public void deleteBook(Long id) {
        bookMapper.deleteById(id);
    }

    @Override
    public void updateBookCover(Long id, String coverImage) {
        Book book = new Book();
        book.setId(id);
        book.setCoverImage(coverImage);
        bookMapper.update(book);
    }

    @Override
    public void updateAvailableCopies(Long id, Integer availableCopies) {
        Book book = getBookById(id);
        if (book == null) {
            throw new RuntimeException("书籍不存在");
        }
        if (availableCopies < 0 || availableCopies > book.getTotalCopies()) {
            throw new RuntimeException("可借数量无效");
        }
        bookMapper.updateAvailableCopies(id, availableCopies);
    }

    @Override
    public List<Book> searchBooksByTitle(String title) {
        return bookMapper.searchByTitle(title);
    }
} 